import base64
import datetime
import requests
from io import BytesIO
import time
import json
import os
from PIL import Image

def img_2_base64(img):
    output_buffer = BytesIO()
    img.save(output_buffer, format='PNG')
    byte_data = output_buffer.getvalue()
    base64_str = str(base64.b64encode(byte_data),'utf8')
    return base64_str

def recognize_captcha(test_path, save_path, image_suffix):
    image_file_name = 'captcha.{}'.format(image_suffix)

    im = Image.open(test_path)

    # 识别
    s = time.time()
    url = "http://127.0.0.1:80/discern"
    base64_str = img_2_base64(im)
    print(base64_str)
    data = json.dumps({'v_code': base64_str})
    r = requests.post(url=url, data=data)
    e = time.time()

    # 识别结果
    print("接口响应: {}".format(r.text))
    predict_text = json.loads(r.text)["v_code"]
    now_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    print("【{}】 耗时：{}ms 预测结果：{}".format(now_time, int((e - s) * 1000), predict_text))

    # 保存文件
    img_name = "{}_{}.{}".format(predict_text, str(time.time()).replace(".", ""), image_suffix)
    path = os.path.join(save_path, img_name)
    im.save(path)
    print("============== end ==============")


def recognize_test_folder():
    '''
        格式化文件夹图片
        :param filepath:
        :param newFilepath:
        :return:
        '''
    # 配置相关参数
    test_path = r"./test/old"  # 测试识别的图片路径
    save_path = r"./test/new"  # 保存的地址
    image_suffix = 'png'
    fileList = os.listdir(test_path)
    for i in fileList:
        recognize_captcha(test_path + '/' + i, save_path, image_suffix)
    print('格式化完成')


if __name__ == '__main__':
    # main()
    recognize_test_folder()
